package com.wys.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wys.common.utils.MyStrUtil;
import com.wys.mall.product.service.CategoryBrandRelationService;
import com.wys.mall.product.vo.Catelog2Vo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wys.common.utils.PageUtils;
import com.wys.common.utils.Query;

import com.wys.mall.product.dao.CategoryDao;
import com.wys.mall.product.entity.CategoryEntity;
import com.wys.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import static java.util.stream.Collectors.toMap;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @CacheEvict(value = "category", allEntries = true) //删除category分区所有的cache
//    @Caching(evict = {
//            @CacheEvict(value = "category", key="'getOneLevelCategories'"),
//            @CacheEvict(value = "category", key="'getCategoryJson'")
//    })
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        //删除分类缓存
//        redisTemplate.delete("categoryJson");
    }

    /**
     * 㞡现树形结构
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装
        //2.1) 所到所有的一级类别 ,parentId = 0
        List<CategoryEntity> levelOneMenus = entities.stream()
                .filter(item -> item.getParentCid() == 0)
                .map(item -> {
                    item.setChildren(this.getChildrens(item, entities));
                    return item;
                })
                .sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                })
                .collect(Collectors.toList());
        return levelOneMenus;
    }

    /**
     * 递归查找菜单所有的子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> treeMenus = all.stream()
                //如果菜单中的父菜单Id == 当前菜单的id，则说明是子菜单
                .filter(item -> Objects.equals(item.getParentCid(), root.getCatId()))
                .map(item -> {
                    //递归添加子菜单
                    List<CategoryEntity> childrens = getChildrens(item, all);
                    item.setChildren(childrens);
                    return item;
                })
                //排序
                .sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                })
                .collect(Collectors.toList());
        return treeMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查录前删除的菜单，id是否被引用
        int result = baseMapper.deleteBatchIds(asList);
    }

    /**
     * 查找当前categoryId所在的完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPaths = this.findParentPath(catelogId, paths);
        Collections.reverse(parentPaths);
        return parentPaths.toArray(new Long[parentPaths.size()]);
    }

    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotBlank(category.getName())) {
            categoryBrandRelationService.updateCategory(category);
            //TODO 更新其它关联分类
        }
    }

    @Override
    @Cacheable(value = {"category"}, key = "#root.methodName") //如果缓存中有，方法都不调用
    public List<CategoryEntity> getOneLevelCategories() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }


    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != null && entity.getParentCid() != 0) {
            this.findParentPath(entity.getParentCid(), paths);
        }
        return paths;
    }

    @Cacheable(value = "category", key = "#root.methodName", sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCategoryJson() {
        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = this.getParentCId(selectList, 0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCId(selectList, v.getCatId());
            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(item2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item2.getCatId().toString(), item2.getName().toString());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParentCId(selectList, item2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(item3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(item2.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parentCid;
    }

    /**
     * redis缓存问题
     * 1、缓存穿透： 缓存穿透是指缓存和数据库中都没有的数据，而用户不断发起请求，
     * 解决方法：将空结果也缓存
     * 2、缓存雪崩：缓存数据大面积失效，而此时又有大量查询这些数据的请求，导致直接查询数据库，
     * 解决方法：设置过期时间+随机数
     * 3、缓存击穿：缓存击穿是指缓存中没有但数据库中有的数据（一般是缓存时间到期），
     * 这时由于并发用户特别多，同时读缓存没读到数据，又同时去数据库去取数据，引起数据库压力瞬间增大，造成过大压力
     * 解决方法：添加锁
     *
     * @return
     */

    public Map<String, List<Catelog2Vo>> getCategoryJson2() {
        //从缓存中取出类别缓存
        String categoryJson = redisTemplate.opsForValue().get("categoryJson");
        Map<String, List<Catelog2Vo>> map = null;
        if (MyStrUtil.isEmpty(categoryJson)) {
            //从数据库查询类别
            map = this.getCategoryJsonFromDbByRedission();
//            map = this.getCategoryJsonFromDb();
        } else {
            //将数据转化成要输出的集合
            map = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }
        return map;
    }

    public Map<String, List<Catelog2Vo>> getCategoryJsonFromDbByRedission() {
        //1、分布式锁
        RLock rLock = redissonClient.getLock("categoryJsonLock");
        rLock.lock();
        //3、加载数据
        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try {
            dataFromDb = this.getDataFromDb();
        } finally {
            rLock.unlock();
        }
        return dataFromDb;
    }

    public Map<String, List<Catelog2Vo>> getCategoryJsonFromDbByRedisLock() {
        //1、分布式锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //2、设置锁过期时间
            //redisTemplate.expire("lock", 30, TimeUnit.SECONDS);
            //3、加载数据
            Map<String, List<Catelog2Vo>> dataFromDb = null;
            try {
                dataFromDb = this.getDataFromDb();
            } finally {
                //4、获得锁value
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            //5、对比，删除自己的锁
//            if(StringUtils.isNotBlank(lockValue) && lockValue.equalsIgnoreCase(uuid)){
//                redisTemplate.delete("lock");
//            }
                //4、使用lua脚本删除锁
                String lua = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(lua, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        } else {
            //5、重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
            }
            return getCategoryJsonFromDbByRedisLock();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        //查询全部
        List<CategoryEntity> allCategories = baseMapper.selectList(null);
        System.out.println("查询了数据库......");
        List<CategoryEntity> level1Categories = this.getParentCId(allCategories, 0L);
        if (CollectionUtils.isNotEmpty(level1Categories)) {
            Map<String, List<Catelog2Vo>> map = level1Categories.stream().collect(toMap(k -> String.valueOf(k.getCatId()), v -> {
                List<Catelog2Vo> catelog2Vos = null;
                //查询二级
                List<CategoryEntity> categories2 = this.getParentCId(allCategories, v.getCatId());
                if (CollectionUtils.isNotEmpty(categories2)) {
                    catelog2Vos = categories2.stream().map(item2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item2.getCatId().toString(), item2.getName());
                        //查询三级
                        List<CategoryEntity> categories3 = this.getParentCId(allCategories, item2.getCatId());
                        if (CollectionUtils.isNotEmpty(categories3)) {
                            List<Catelog2Vo.Category3Vo> category3Vos = categories3.stream().map(item3 -> {
                                Catelog2Vo.Category3Vo vo3 = new Catelog2Vo.Category3Vo(item2.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                                return vo3;
                            }).collect(Collectors.toList());
                            //设置到二级中
                            catelog2Vo.setCatalog3List(category3Vos);
                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }
                return catelog2Vos;
            }));
            //将读到新的类别数据添加到缓存中，【1, TimeUnit.DAYS表示一天过期】
            redisTemplate.opsForValue().set("categoryJson", JSON.toJSONString(map), 1, TimeUnit.DAYS);
            return map;
        }
        return null;
    }

    public Map<String, List<Catelog2Vo>> getCategoryJsonFromDb() {
        //查询一级
//        List<CategoryEntity> level1Categories = this.getOneLevelCategories();
        //查询全部
        synchronized (this) {
            return this.getDataFromDb();
        }
    }

    /**
     * 查询子节点
     *
     * @param entities
     * @param parentCid
     * @return
     */
    public List<CategoryEntity> getParentCId(List<CategoryEntity> entities, Long parentCid) {
        return entities.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
    }
//    private List<CategoryEntity> getParentCId(CategoryEntity categoryEntity) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", categoryEntity.getCatId()));
//    }
}